package com.irdstudio.bsp.executor.rest.init;
/**
 * 激活控制台执行节点
 * 1、注册地址到节点s_agent_info
 * 2、激活执行节点（加载定时任务，此处指内部管理作业)
 * @author ligm
 * @date 2020-12-10
 */
import com.irdstudio.bsp.executor.core.dao.SAgentInfoDao;
import com.irdstudio.bsp.executor.core.dao.domain.SAgentInfo;
import com.irdstudio.bsp.executor.core.tinycore.jdbc.dbcp.TConnPool;
import com.irdstudio.bsp.executor.rest.enums.ExecutorStateEnum;
import com.irdstudio.bsp.executor.rest.schedule.ScheduleJobUtil;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class ActiveConsoleExecutor {

	// 此类为示例代码，展示思路
	private ActiveConsoleExecutor() { }

	/**
	 * 注册控制台执行节点到s_agent_info
	 * @return
	 */
	private boolean registerConsoleExecutor() {
		// 执行节点地址注册为：http://127.0.0.1:8080/sop-console-web/executor
		Connection conn=null;
		try{
			List<Object> values = new ArrayList<>();
			conn= TConnPool.getDefaultPool().getConnection();
			SAgentInfoDao sAgentInfoDao=new SAgentInfoDao(conn);
			SAgentInfo sAgentInfo=new SAgentInfo();
			sAgentInfo.setAgentId(ExecutorInstInfo.EXECUTOR_ID);
			SAgentInfo result=sAgentInfoDao.queryByPk(sAgentInfo);
			if(result!=null){
				result.setAgentState(ExecutorStateEnum.RUNING.getCode());
				sAgentInfoDao.updateByPk(result);
			}else{
				result=new SAgentInfo();
				result.setAgentId(ExecutorInstInfo.EXECUTOR_ID);
				result.setAgentName(ExecutorInstInfo.EXECUTOR_ID);
				result.setAgentState(ExecutorStateEnum.RUNING.getCode());
				result.setAgentUrl("http://127.0.0.1:8080/bsp-console-web/executor");
				sAgentInfoDao.insertSAgentInfo(result);
			}
			return true;
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			TConnPool.getDefaultPool().releaseConnection(conn);
		}
		return false;
	}

	/**
	 * 激活控制台执行节点并加载对应的的定时任务
	 */
	private void activeConsoleExecutor() {

		ExecutorInstInfo.EXECUTOR_ID = "console-executor";

		if(registerConsoleExecutor()) {
			// 加载需要在Agent执行的定时任务
			ScheduleJobUtil.loadJobsForExecutor();
		}
		// 设定Agent实例为“已激活”
		ExecutorInstInfo.EXECUTOR_STATE = ExecutorStateEnum.RUNING.getCode();

	}
}
